package com.i1314i.reportsystem.service.user.impl;

import com.i1314i.reportsystem.mapper.AdminUserMapper;
import com.i1314i.reportsystem.mapper.RoleMapper;
import com.i1314i.reportsystem.mapper.UserMapper;
import com.i1314i.reportsystem.po.*;
import com.i1314i.reportsystem.service.user.UserService;
import com.i1314i.reportsystem.shiro.token.CaptchaUsernamePasswordToken;
import com.i1314i.reportsystem.utils.common.TemplateUtils;
import com.i1314i.reportsystem.utils.inimsg.UserMsgUtils;
import com.i1314i.reportsystem.utils.redisToken.TokenUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * @author 平行时空
 * @created 2018-09-18 19:51
 **/

@Service("userService")
public class UserServiceimpl implements UserService {
    private Logger logger= LoggerFactory.getLogger(UserServiceimpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private ResultMap resultMap;

    /**
     * 按用户名查找User
     * @param username
     * @return
     */
    @Override
    public User selectUserByUserName(String username) {
        User user=userMapper.selectUserByUserName(username);
        Role role=null;
        List<Role>roleList=null;
        if(user!=null){
             role=roleMapper.selectRoleById(user.getRoleid());
            roleList=roleMapper.getRolePermission(role.getRole());
        }

        user.setRole(role);
        user.setRoleList(roleList);
        return user;
    }

    /**
     * 按用户名查找AdminUser
     * @param username
     * @return
     */
    
    @Override
    public AdminUser selectAdminUserByUserName(String username) {
        AdminUser user=adminUserMapper.selectAdminUserByUserName(username);
        Role role=null;
        List<Role>roleList=null;
        if(user!=null){
             role=roleMapper.selectRoleById(user.getRoleid());
             roleList=roleMapper.getRolePermission(role.getRole());
        }

        user.setRole(role);
        user.setRoleList(roleList);
        return user;
    }


    /**
     * 用户登录
     * @param user
     * @return
     * @throws IOException
     */
    @Override
    public ResultMap login(User user) throws IOException {

        Code code=new Code(user.getCodetoken(),user.getCode());
        //3、得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
        Subject subject = SecurityUtils.getSubject();
        CaptchaUsernamePasswordToken usernamePasswordToken = new CaptchaUsernamePasswordToken(user.getUsername(), user.getPassword(),code);
        subject.login(usernamePasswordToken);
        PrincipalCollection principalCollection = subject.getPrincipals();
        logger.info(user.getUsername()+":"+UserMsgUtils.login_success_msg);
        Set<String>stringSet=principalCollection.getRealmNames();

        for (String realmName:stringSet
                ) {
            if("userLoginRealm".equalsIgnoreCase(realmName)){
                return getUserToken(user);
            }else if("adminLoginRealm".equalsIgnoreCase(realmName)){
                return getAdminUserToken(user);
            }
        }
        return resultMap;
    }


    /**
     * 管理员登陆
     * @param user
     * @return
     */
    protected ResultMap getAdminUserToken(User user){
        AdminUser adminUser=null;
        try{
            adminUser=selectAdminUserByUserName(user.getUsername());
        }catch (Exception e){
            logger.info(user.getUsername()+" :admin登陆数据库查询错误");
            return  resultMap.code(UserMsgUtils.login_error_code)
                    .msg(UserMsgUtils.login_error_msg);
        }

        Token token=null;

        if(adminUser!=null){
            String gettoken="usertoken_"+TokenUtils.makeToken();
            boolean tokenvalue=TokenUtils.makeToken(AdminUser.class,adminUser,gettoken);

            if(tokenvalue){
                token=new Token();
                token.setToken(gettoken);
                 if(adminUser.getType()==1){  //学院
                     resultMap.code(UserMsgUtils.admin_college_success_code)
                             .msg(UserMsgUtils.admin_login_success_msg)
                             .data(token);
                 }else if(adminUser.getType()==2){  //学校
                     resultMap.code(UserMsgUtils.admin_school_success_code)
                             .msg(UserMsgUtils.admin_login_success_msg)
                             .data(token);
                 }else if(adminUser.getType()==3){//超级
                     resultMap.code(UserMsgUtils.admin_login_success_code)
                             .msg(UserMsgUtils.admin_login_success_msg)
                             .data(token);
                 }
            }


        }else {
            return  resultMap.code(UserMsgUtils.login_error_code)
                    .msg(UserMsgUtils.login_error_msg);
        }

        return resultMap;
    }


    /**
     * 用户登录
     * @param user
     * @return
     */
    protected ResultMap getUserToken(User user){
        User usersql=null;
        try{
            usersql=selectUserByUserName(user.getUsername());
        }catch (Exception e){
            logger.info(user.getUsername()+" :user登陆数据库查询错误");
            return  resultMap.code(UserMsgUtils.login_error_code)
                    .msg(UserMsgUtils.login_error_msg);
        }

        Token token=null;

        if(user!=null){
            String gettoken="usertoken_"+TokenUtils.makeToken();
            boolean tokenvalue=TokenUtils.makeToken(User.class,usersql,gettoken);

            if(tokenvalue){
                token=new Token();
                token.setToken(gettoken);
                    resultMap.code(UserMsgUtils.login_success_code)
                            .msg(UserMsgUtils.login_success_msg)
                            .data(token);
                }
            }else{
            return  resultMap.code(UserMsgUtils.login_error_code)
                    .msg(UserMsgUtils.login_error_msg);
        }

        return resultMap;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public ResultMap regUser(User user) {

        User usersql=selectUserByUserName(user.getUsername());

        if(usersql==null){

        }

        return null;
    }



    /**
     * shiro用户登录处理类
     * @param user
     */
    protected void loginData(User user) {

    }


    protected void loginData(String username, String password) {
        //3、得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
        Subject subject = SecurityUtils.getSubject();
       // UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        CaptchaUsernamePasswordToken token=new CaptchaUsernamePasswordToken(username,password,new Code());
        subject.login(token);
        //得到一个身份集合，其包含了第一个Realm验证成功的身份信息
        PrincipalCollection principalCollection = subject.getPrincipals();
        System.out.println(principalCollection.asList().size());
    }



    public void tests() throws IOException {
        User user=new User();
        user.setPassword("123s");
        user.setUsername("liu");
        login(user);
    }


    public static void main(String[] args) {
        System.out.println(TemplateUtils.uuid());
    }

}
